// pages/myClassTeacher/myClassTeacher.js
let klassModel = require('../../models/klass.js')
let userModel = require('../../models/user.js')
let request = require('../../operation/operation.js')
let bxt = require('../../utils/bxt.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    teachers:[],
    canDel: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getClassTeachers()
    this.initUserPower()
    getApp().notificationCenter.register(bxt.DELETE_TEACHER_MESSAGE, this, "handleDelTeacherMessage");
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    getApp().notificationCenter.remove(bxt.DELETE_TEACHER_MESSAGE, this)
  },

  onShowTeacherInfo: function (event) {
    if (this.data.canDel) {
      getApp().globalData.param = event.currentTarget.dataset.teacher

      wx.navigateTo({
        url: '../teacherInfo/teacherInfo?mode=del'
      })
    }
  },

  initUserPower: function () {
    this.setData({
      canDel: userModel.checkUserManager()
    })
  },

  getClassTeachers: function () {
    let currentClass = klassModel.getCurrentClass(), that = this
    request.getRequest('/teachers?klassSid=' + currentClass.sid, {}, true)
      .then(res => {
        var data = res.data;
        if (request.SUCCESSED == data.status) {
          that.setData({
            teachers: data.items
          })
        } else {
          wx.showToast({
            title: data.msg,
            iocn: 'none'
          })
        }
      })
      .catch(e => {
        console.log(e)
      })
  },

  handleDelTeacherMessage: function (object) {
    let teachers = this.data.teachers

    for (let index = 0, length = teachers.length; index < length; index++) {
      if (object.teacher.sid == teachers[index].sid) {
        teachers.splice(index, 1)
        break
      }
    }

    this.setData({
      teachers: teachers
    })
  }

})